package linestrategy

import (
	"codejy/analysis/lineanalysis"
	"codejy/globalfunc"
	"codejy/store"
	"codejy/structdef"
	"codejy/utils"
	"strings"
)

// 类型行为内使用this.方法调用策略
type MultiLineStrStrategy struct {
}

// 注册策略
func init() {
	RegisterStrategy(&MultiLineStrStrategy{})
}

func (m MultiLineStrStrategy) getId() int {
	return lineanalysis.MultiLineString
}

func (m MultiLineStrStrategy) Execute(threadStore *structdef.ThreadStore) {
	oldCode := threadStore.Code
	codes := threadStore.Codes
	var strline string
	//获取当前执行指针
	currentPointer := threadStore.CurrentPoint
	length := len(codes)
	//从当前行的下一行开始,直到遇到"""
	for i := currentPointer + 1; i < length; i++ {
		code := codes[i].LineContent
		if code == `"""` {
			//设置当前执行指针和当前行
			threadStore.CurrentPoint = i
			break
		}
		//字符串大括号中的内容,解析
		brackets, p := utils.GetStrBigBrackets(code)
		if p {
			for i1 := range brackets {
				value := globalfunc.ExecuteFunc("AssignmentStrategyMode", threadStore, brackets[i1]).(string)
				//如果是字符串,那么就去掉""
				if strings.HasPrefix(value, "\"") && strings.HasSuffix(value, "\"") {
					value = strings.ReplaceAll(value, "\"", "")
				}
				//替换
				code = strings.ReplaceAll(code, "${"+brackets[i1]+"}", value)
			}
		}

		strline += code + "\n"
	}
	//去除最后一个换行符
	strline = strings.TrimRight(strline, "\n")
	//获取变量名,通过获取第一个等号的位置
	index := strings.Index(oldCode.LineContent, "=")
	variableName := oldCode.LineContent[:index]
	//去掉开头var
	variableName = variableName[3:]
	//注册变量
	store.RegisterVariable(threadStore, structdef.NewVarDefinitionValue(variableName, "\""+strline+"\"", lineanalysis.MultiLineString))

}
